var selectedDataRow = '', selectedRecordRow = '';
var s_operType = 'revoke';
var isInit = true;
var vueObj = new Vue({
    el: "#vue",
    data: {
        orgObj: defOrgInfo
    }
});

$(function () {
    newCheck.initByName('_reason');
    window.actionEvents = {
        'click .infoView': function(e, value, row, index) {
            //编辑操作
            selectedDataRow = row;
            openInfoOrgPage();
        },
        'click .isvInfoView': function(e, value, row, index) {
            //编辑操作
            selectedDataRow = row;
            openCommonIsvPage(row.isvPid, 'org');
        },
    }
    initTextSearch("#isvName",
        basePath + 'org/getIsvData?t='+new Date().getTime()+'&isvName=',
        ['isvPid', 'isvName'],
        {'isvPid':'服务商PID', 'isvName':'服务商名称'},
        'isvPid',
        'isvName',
        true,
        selectIsvValue,
        noSelectIsvValue,
        false);
});

$('#setReasonPage').on('hidden.bs.modal', function () {
    // 执行一些动作...
    $("input[type=checkbox][name=_reason]").removeAttr("checked");
    $('#reason').val('');
});

function selectIsvValue(data) {
    if (!data || !data.isvPid) {
        return;
    }
    $('#isvPid').val(data.isvPid);
}

function noSelectIsvValue() {
    $('#isvPid').val('');
}

function doRefresh() {
    selectedDataRow = '';
    var orgName = $('#orgName').val();
    var status = $('#status').val();
    var dataStatus = $('#dataStatus').val();
    var provinceCode = $('#province').val();
    var cityCode = $('#city').val();
    var isMerge = $('#isMerge').val();
    var isvPid = $('#isvPid').val();
    $('#dataTable').bootstrapTable('refresh', {
        url: basePath + 'org/pageFindOrgData?t=' + new Date().getTime(),
        query: {
            orgName : orgName,
            status : status,
            dataStatus : dataStatus,
            orgProvinceCode : provinceCode,
            orgCityCode : cityCode,
            isMerge : isMerge,
            isvPid : isvPid,
        },
    });
}

function doRecordRefresh() {
    selectedRecordRow = '';
    var orgCode = selectedDataRow.orgCode;
    $('#recordTable').bootstrapTable('refresh', {
        url: basePath + 'org/pageFindRecordData?t=' + new Date().getTime(),
        query: {
            bizCode : orgCode,
        },
    });
}

function getRecordParams(params) {
    var orgCode = selectedDataRow.orgCode;
    return {
        bizCode : orgCode,
        pageSize : params.pageSize,
        pageNo : params.pageNumber
    };
}

function getParams(params) {
    var orgName = $('#orgName').val();
    var status = $('#status').val();
    var dataStatus = $('#dataStatus').val();
    var provinceCode = $('#province').val();
    var cityCode = $('#city').val();
    var isMerge = $('#isMerge').val();
    var isvPid = $('#isvPid').val();
    var pageSize = params.pageSize;
    var pageNo = params.pageNumber;
    if (isInit) {
        isInit = false;
        pageSize = defOrgInfo.pageSize ? defOrgInfo.pageSize : params.pageSize;
        pageNo = defOrgInfo.pageNo ? defOrgInfo.pageNo : params.pageNumber;
    }
    return {
        orgName : orgName,
        status : status,
        dataStatus : dataStatus,
        orgProvinceCode : provinceCode,
        orgCityCode : cityCode,
        isMerge : isMerge,
        isvPid : isvPid,
        pageSize : pageSize,
        pageNo : pageNo
    };
}

function doSelectCity() {
    var province = $('#province').val();
    if (!province || province == '') {
        $('#city').val('');
        var str = '<option value="">--请选择--</option>';
        $('#city').html(str);
        doRefresh();
    } else {
        province = province.substring(0, 2);
        var postData = {
            dictCode : province,
            groupCode : 'CITY_CODE'
        };
        $.ajax({
            type: 'post',
            url: basePath + 'org/selectCity?t=' + new Date().getTime(),
            dataType: 'json',
            data: postData,
            success : function (data) {
                if(data && data.result){
                    setCitySelect(data.content);
                }else if(data&&!data.result){
                    toastr.error(data.message);
                }else{
                    toastr.error('获取城市信息失败');
                }
            },
            error: function (request) {
                delayToastr(common_system_error);
            }
        });
    }
}

function setCitySelect(cityList) {
    $('#city').val('');
    var htmlStr = '<option value="">--请选择--</option>';
    if (cityList) {
        for (var i=0; i<cityList.length; i++) {
            htmlStr += '<option value="'+cityList[i].code+'">'+cityList[i].name+'</option>';
        }
    }
    $('#city').html(htmlStr);
    doRefresh();
}

function openAddOrgPage() {
    openEditPage('add', 0);
}

function openEditOrgPage() {
    if (!selectedDataRow || selectedDataRow == '') {
        toastr.error(common_no_choose_msg.format("编辑"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error('待审核的机构无法直接编辑');
        return;
    }
    openEditPage('edit', selectedDataRow.id);
}

function openInfoOrgPage() {
    if (!selectedDataRow || selectedDataRow == '') {
        toastr.error(common_no_choose_msg.format("操作"));
        return;
    }
    openEditPage('info', selectedDataRow.id);
}

function openEditPage(command, id) {
    var tableOptions = $('#dataTable').bootstrapTable('getOptions', null);
    window.location.href = basePath + 'org/editOrgPage?type=' + command + '&id=' + id + '&t=' + new Date().getTime() +
        '&' + $('#searchForm').serialize() + '&pageNo=' + tableOptions.pageNumber + '&pageSize=' + tableOptions.pageSize;
}

function checkOrgRevoke() {
    if (!selectedDataRow || selectedDataRow == '') {
        toastr.error(common_no_choose_msg.format("撤销"));
        return;
    }
    if (selectedDataRow.status != 'publish') {
        toastr.error("未发布的机构不能撤销");
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error("待审核的机构不能撤销");
        return;
    }
    showSetReasonPage('revoke');
}

function checkOrgDelete() {
    if (!selectedDataRow || selectedDataRow == '') {
        toastr.error(common_no_choose_msg.format("删除"));
        return;
    }
    if (selectedDataRow.status == 'publish') {
        toastr.error("已发布的机构不能直接删除");
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error("待审核的机构不能删除");
        return;
    }
    var postData = {
        id : selectedDataRow.id,
        orgCode : selectedDataRow.orgCode
    };
    $.ajax({
        type: 'post',
        url: basePath + 'org/checkOrgDelete',
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if (!data) {
                toastr.error('校验删除失败');
                return;
            }
            if (!data.isSuccess) {
                if (data.errorCode == 'EXIST') {
                    toastr.error('机构与业务数据关联，无法删除');
                } else {
                    toastr.error(data.errorDesc);
                }
            } else {
                showSetReasonPage('delete');
            }
            return;
        },
    });
}

function showSetReasonPage(type) {
    s_operType = type;
    if (type == 'delete') {
        $('#_modelTitle').html('删除');
        $('#_modelTip').html('删除');
    } else {
        $('#_modelTitle').html('撤销发布');
        $('#_modelTip').html('撤销发布');
    }
    $('#setReasonPage').modal('show');
}

function closeSetReasonPage() {
    $('#setReasonPage').modal('hide');
    $("input[type=checkbox][name=_reason]").removeAttr("checked");
    $('#reason').val('');
}

function doSaveReason() {
    if (s_operType == 'delete') {
        deleteOrg();
    } else if (s_operType == 'revoke') {
        doRevoke();
    } else {
        toastr.error(common_system_error);
    }
}

function deleteOrg() {
    var reason = getReasonData();
    if (!reason || reason == '') {
        toastr.error('删除原因不能为空');
        return;
    }
    var postData = {
        id : selectedDataRow.id,
        reason : reason
    };
    $.ajax({
        type: 'post',
        url: basePath + 'org/deleteOrg?t=' + new Date().getTime(),
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            if(data && data.isSuccess){
                toastr.success('删除成功');
                closeSetReasonPage();
                doRefresh();
            }else if(data&&!data.isSuccess){
                toastr.error(data.errorDesc);
            }else{
                toastr.error('删除失败');
            }
        },
        error: function (request) {
            toastr.error(common_system_error);
        }
    });
}

function doCommit() {
    if (!selectedDataRow || selectedDataRow == '') {
        toastr.error(common_no_choose_msg.format("提交发布"));
        return;
    }
    if (selectedDataRow.dataStatus == 'pending_check') {
        toastr.error('待审核的机构无法提交发布');
        return;
    }
    if (selectedDataRow.dataStatus == 'check_pass' || selectedDataRow.status == 'check_fail') {
        toastr.error('该机构没有修改，无需发布');
        return;
    }
    var str = '确认提交发布吗？';
    swalToastr('提交发布', str, 'warning', doCommitOrg, '确认提交');
}

function doCommitOrg() {
    var postData = {
        id : selectedDataRow.id,
        orgCode : selectedDataRow.orgCode,
        orgMergeCode : selectedDataRow.orgMergeCode
    };
    showLoading();
    $.ajax({
        type: 'post',
        url: basePath + 'org/commitOrg?t=' + new Date().getTime(),
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            hideLoading();
            if (!data) {
                toastr.error('提交失败');
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
            toastr.success('提交成功，等待管理员审核！');
            doRefresh();
            return;
        },
    });
}

function getReasonData() {
    var checks=$('input[name="_reason"]:checked');
    var str = '';
    checks.each(function(idx,element){
        str += $(element).val() + ',';
    });
    var reason = $.trim($('#reason').val());
    str += reason;
    if (!reason || reason == '') {
        str = str.length > 0 ? str.substring(0, str.length - 1) : '';
    }
    return str;
}

function doRevoke() {
    var reason = getReasonData();
    if (!reason || reason == '') {
        toastr.error('撤销原因不能为空');
        return;
    }
    var postData = {
        id : selectedDataRow.id,
        orgCode : selectedDataRow.orgCode,
        reason : reason
    };
    showLoading();
    $.ajax({
        type: 'post',
        url: basePath + 'org/revokeOrg?t=' + new Date().getTime(),
        dataType: 'json',
        contentType: "application/json",
        data: JSON.stringify(postData),
        success : function (data) {
            hideLoading();
            if (!data) {
                toastr.error('撤销失败');
                return;
            }
            if (!data.isSuccess) {
                toastr.error(data.errorDesc);
                return;
            }
            toastr.success('撤销发布成功');
            closeSetReasonPage();
            doRefresh();
            return;
        },
    });
}

function doExport() {
    $('#searchForm').attr("action",basePath+"org/exportOrgDataExcel?t=" + new Date().getTime());
    $('#searchForm').submit();
}

//------------------------------------------------------------------------列表数据初始化
function formatStatus(value, row, index) {
    if (value == 'publish') {
        return '已发布';
    }
    if (value == 'unpublished') {
        return '未发布';
    }
    return value;
}

function formatDataStatus(value, row, index) {
    if (value == 'pending_pub') {
        return '待提交';
    }
    if (value == 'pending_check') {
        return '待审核';
    }
    if (value == 'check_pass') {
        return '审核通过';
    }
    if (value == 'check_fail') {
        return '审核不通过';
    }
    if (value == 'revoke') {
        return '已撤销';
    }
    return value;
}

function formatCheckType(value, row, index) {
    if (checkTypeList) {
        for (var i=0; i<checkTypeList.length; i++) {
            if (value == checkTypeList[i].key) {
                return checkTypeList[i].value;
            }
        }
    }
    return value;
}

function formatResult(value, row, index) {
    if (checkResultTypeList) {
        for (var i=0; i<checkResultTypeList.length; i++) {
            if (value == checkResultTypeList[i].key) {
                return checkResultTypeList[i].value;
            }
        }
    }
    return value;
}

//------------------------------------------------------------------------列表选中事件
//左边选中事件
$("#dataTable").on("click-row.bs.table",function(e,row,ele){
    $("#dataTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedDataRow = row;
    doRecordRefresh();
});
//右边选中事件
$("#recordTable").on("click-row.bs.table",function(e,row,ele){
    $("#recordTable .success").removeClass("success");
    $(ele).addClass("success");
    selectedRecordRow = row;
});
